import Axios from "axios";
import store from "src/store";
import config from '../config'

Axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
Axios.defaults.withCredentials = true;
// Add a request interceptor
Axios.interceptors.request.use(
    config => {
        // Do something before request is sent
        const key = `${config.method.toLowerCase()} ${config.url}`;
        store.commit("loading", { [key]: true });
        return { ...config };
    },
    error => {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
Axios.interceptors.response.use(
    response => {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        const { config } = response;
        const key = `${config.method.toLowerCase()} ${config.url}`;
        store.commit("loading", { [key]: false });
        return response;
    },
    error => {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        const { config } = error;
        if (config) {
            const key = `${config.method.toLowerCase()} ${config.url}`;
            store.commit("loading", { [key]: false });
        }
        return Promise.reject(error);
    }
);
const axios = Axios.create(config);

export default axios;
